import type { Map, MapMouseEvent } from 'mapbox-gl'
import type { LngLat } from '@/geom/great-circle'
import { overlay, type LineFeature } from '@/map'
import { IgnoreMouseDrag, isRight, type InteractionTip } from '@/map-interaction'
import { highLightProperties } from '@/map/highlights'
import { addAuxLine } from './core'

export class DrawAuxLine extends IgnoreMouseDrag {
  public readonly type: string = 'DrawAuxLine'
  public start: LngLat | null = null

  public readonly tip: InteractionTip = {
    title: '绘制测量线',
    content: '1. 左键点击绘制测量线.\n2. 右键取消绘制.'
  }

  public attach(map: Map): void {
    super.attach(map)
    map.getCanvas().style.cursor = 'crosshair'
  }

  public detach(map: Map): void {
    map.getCanvas().style.cursor = 'auto'
    super.detach(map)
  }
  public onMouseMove(evt: MapMouseEvent): void {
    const start = this.start
    if (!start) {
      return
    }
    const end = evt.lngLat
    const lf: LineFeature = {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [
          [start.lng, start.lat],
          [end.lng, end.lat]
        ]
      },
      properties: highLightProperties.line.primary
    }
    overlay.updateLine(lf)
  }

  public onMouseClick(evt: MapMouseEvent): void {
    if (isRight(evt)) {
      this.finish()
      return
    }
    const { lng, lat } = evt.lngLat
    const pt = { lng, lat }
    if (!this.start) {
      this.start = pt
      return
    }
    addAuxLine(this.start, pt)
    this.finish()
  }
}
